<script setup lang="ts">
import { OrderType } from '@/enums'
import { uploadImage } from '@/services/consult'
import type { Image } from '@/types/consult'
import { closeToast, showLoadingToast, showToast } from 'vant'
import type { UploaderAfterRead } from 'vant/lib/uploader/types'
import { ref } from 'vue'

withDefaults(
  defineProps<{
    status: OrderType
  }>(),
  { status: OrderType.ConsultWait } // 默认就是待接诊
)

const emit = defineEmits<{
  (e: 'send-text', text: string): void
  (e: 'send-image', image: Image): void
}>()

const text = ref('')

const onEnter = () => {
  emit('send-text', text.value)
  // 清空输入框文本
  text.value = ''
}

const onAfterRead: UploaderAfterRead = (item) => {
  if (!Array.isArray(item)) {
    console.log('[ item.file ] >', item.file)

    // 上传图片之前，转起来
    showLoadingToast('发送中...')

    uploadImage(item.file as File).then((res) => {
      emit('send-image', res.data)
      // 上传成功后，关闭（单例模式）
      closeToast()
    })
  }
}

const onOversize = () => {
  showToast('图片大小不能超过 2 MB')
}
</script>

<template>
  <div class="room-action">
    <van-field
      v-model="text"
      type="text"
      class="input"
      :border="false"
      placeholder="问医生"
      autocomplete="off"
      :disabled="status !== OrderType.ConsultChat"
      @keyup.enter="onEnter"
    ></van-field>
    <van-uploader
      :max-size="500 * 1024"
      @oversize="onOversize"
      :preview-image="false"
      :disabled="status !== OrderType.ConsultChat"
      :after-read="onAfterRead"
    >
      <cp-icon name="consult-img" />
    </van-uploader>
  </div>
</template>

<style lang="scss" scoped>
.room-action {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 1;
  box-sizing: border-box;
  .input {
    background-color: var(--cp-bg);
    border: none;
    border-radius: 25px;
    margin-right: 10px;
    padding: 8px 15px;
  }
  .cp-icon {
    width: 24px;
    height: 24px;
  }
}
</style>
